<style>
  .picImg {
    width: 40px;
    height: 40px;
  }
</style>
<template>
  <div class="app-container">
    <!--&lt;!&ndash; 查询和其他操作 &ndash;&gt;-->
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit"
                 @click="handleAdd">新增
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
              :header-cell-style="{background:'#92D3FF',color:'#fff'}">

      <el-table-column align="center" min-width="100" label="用户名" prop="userName"/>
      <el-table-column align="center" min-width="100" label="姓名" prop="realName"/>
      <el-table-column align="center" min-width="100" label="所属公司类型" prop="companyType">
        <template slot-scope="scope">
          <span>{{scope.row.companyType | companyTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" label="所属公司" prop="companyName"/>
      <el-table-column align="center" min-width="100" label="最后登录时间" prop="timeLastLogin"/>
      <el-table-column align="center" min-width="100" label="创建时间" prop="timeAdd"/>
      <el-table-column align="center" min-width="100" label="修改时间" prop="timeModify"/>
      <el-table-column align="center" min-width="100" label="电子邮箱" prop="email"/>
      <el-table-column align="center" min-width="100" label="手机号" prop="mobile"/>
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"
                     @click="handleEdit(scope.row)">修改
          </el-button>
          <el-popover
            placement="top"
            width="200"
            trigger="manual"
            :ref="'popover-' + scope.row.userName">
            <p>确定删除该数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.userName].doClose()">取消
              </el-button>
              <el-button type="primary" size="mini" @click="doDelete(scope.row)">确定</el-button>
            </div>
            <el-button type="danger" size="mini" slot="reference"
                       @click="$refs[`popover-` + scope.row.userName].doShow()">删除
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
                @pagination="getList"/>
    <!-- 编辑对话框 -->
    <el-dialog :visible.sync="editDialogVisible" :title="textMap[dialogStatus]" width="700px" :close-on-click-modal="false">
      <el-form ref="editForm" :rules="dialogStatus=='update'?editFormRules:createFormRules" :model="editForm" status-icon label-position="right"
               label-width="110px" style="width: 60%; margin-left:50px;">
        <el-form-item label="用户登录名称" prop="userName">
          <el-input :disabled="dialogStatus=='update'" v-model="editForm.userName" placeholder="用户登录名称"/>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input :disabled="dialogStatus=='update'" type="password" v-model="editForm.password" placeholder="登录密码"/>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="电子邮箱"/>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="手机号"/>
        </el-form-item>
        <el-form-item label="所属公司" prop="companyID">
          <el-select v-model="editForm.companyID" placeholder="请选择" @change="companyChange">
            <el-option
              v-for="item in companies"
              :key="item.ID"
              :label="item.companyName"
              :value="item.ID"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属公司类型" prop="companyType">
          <el-radio-group v-model="editForm.companyType">
            <div style="margin-top: 10px;">
              <el-radio :label="0">保险公司</el-radio>
              <el-radio :label="1" >保代公司</el-radio>
            </div>
            <div style="margin-top: 20px">
              <el-radio :label="2" >保理公司</el-radio>
              <el-radio :label="3" >权益服务商</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="doCreate">确定</el-button>
        <el-button v-else type="primary" @click="doEdit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { doGet, doPost } from '@/api'
  import { cities } from '@/utils/base'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  // import fileUp from '@/components/fileUp' // Secondary package based on el-pagination

  const FETCH_PAGE = 'user.html'
  const FETCH_URL = {
    LIST: `${FETCH_PAGE}?op=list`,
    CREATE: `${FETCH_PAGE}?op=add`,
    EDIT: `${FETCH_PAGE}?op=chg`,
    DELETE: `${FETCH_PAGE}?op=del`,
    COMPANY: `${FETCH_PAGE}?op=getCompanyList`,
    IMPORT: `${FETCH_PAGE}?op=import`
  }
  export default {
    name: 'bank',
    components: { Pagination },
    filters: {
      companyTypeFilter(companyType) {
        return { '0': '保险公司', '1': '保代公司', '2': '保理公司', '3': '权益服务商' }[companyType]
      }
    },
    data() {
      var validateMobile = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入手机号'))
        } else {
          var regMobile = /^1[3456789]\d{9}$/
          if (!regMobile.test(value)) {
            callback(new Error('请输入手机号格式不对'))
          } else {
            callback()
          }
        }

      }
      var validatePwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          var regPassword = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/
          if (!regPassword.test(value)) {
            callback(new Error('密码必须是字母和数字组成，6~18位数'))
          } else {
            callback()
          }
        }

      }
      var validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入邮箱地址'))
        } else {
          var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (!regEmail.test(value)) {
            callback(new Error('邮箱格式不对'))
          } else {
            callback()
          }
        }

      }
      return {
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20
        },
        dialogStatus: undefined,
        companies: [],
        textMap: {
          update: '编辑',
          create: '创建'
        },
        editForm: {
          userName: undefined,
          password: undefined,
          email: undefined,
          realName: undefined,
          mobile: undefined,
          companyType: undefined,
          companyID: undefined
        },
        editFormRules: {
          userName: [{ required: true, message: '用户登录名称不允许为空', trigger: 'blur' }],
          email: [{ validator: validateEmail, trigger: 'blur' }],
          // realName: [{required: true, message: '姓名不允许为空', trigger: 'blur'}],
          mobile: [{ validator:validateMobile, trigger: 'blur' }],
          companyType: [{ required: true, message: '所属公司类型不允许为空', trigger: 'blur' }],
          companyID: [{ required: true, message: '公司名称不允许为空', trigger: 'blur' }]
        },
        createFormRules: {
          userName: [{ required: true, message: '用户登录名称不允许为空', trigger: 'blur' }],
          email: [{ validator: validateEmail, trigger: 'blur' }],
          password: [{ validator: validatePwd, trigger: 'blur' }],
          // realName: [{required: true, message: '姓名不允许为空', trigger: 'blur'}],
          mobile: [{ validator: validateMobile, trigger: 'blur' }],
          companyType: [{ required: true, message: '所属公司类型不允许为空', trigger: 'blur' }],
          companyID: [{ required: true, message: '公司名称不允许为空', trigger: 'blur' }]
        },
        createDialogVisible: false,
        editDialogVisible: false,
        exportDialogVisible: false,
        editIndex: undefined,
        cities: cities
      }
    },
    created() {
      this.getList()
      this.getCompany()
    },
    methods: {
      getCompany() {
        doGet(FETCH_URL.COMPANY, {}).then(response => {
          this.companies = response.rows
        }).catch(() => {
          this.companies = []
        })
      },
      getList() {
        this.listLoading = true
        doGet(FETCH_URL.LIST, this.listQuery).then(response => {
          this.list = response.rows
          this.total = response.data.totalcount
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      /*===addBegin===*/
      handleAdd() {
        this.editForm = {
          userName: undefined,
          password: undefined,
          email: undefined,
          realName: undefined,
          mobile: undefined,
          companyType: 0,
          companyID: undefined,
        }
        this.dialogStatus = 'create'
        this.editDialogVisible = true
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      doCreate() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            doGet(FETCH_URL.CREATE, this.editForm)
              .then(response => {
                this.getList()
                this.editDialogVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.message
                })
              })
          }
        })
      },
      /*===addEnd===*/
      /*===editBegin===*/
      handleEdit(row) {
        this.editForm = Object.assign({}, row)
        this.editIndex = this.list.indexOf(row)
        this.dialogStatus = 'update'
        this.editDialogVisible = true
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      doEdit() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            doGet(FETCH_URL.EDIT, this.editForm)
              .then(response => {
                this.getList()
                this.editDialogVisible = false
                this.list[this.editIndex] = this.editForm
                this.$notify.success({
                  title: '成功',
                  message: '修改成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.message
                })
              })
          }
        })
      },
      /*==editEnd==*/
      /*==deleteBegin==*/
      doDelete(row) {
        doGet(FETCH_URL.DELETE, row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.total--
            this.$refs[`popover-` + row.userName].doClose()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.message
            })
          })
      },
      handleChange(value) {
        console.log(value)
      },
      /*==deleteEnd==*/
      /*==exportBegin==*/
      // handleExport(value) {
      //     this.exportDialogVisible=true;
      // }
      /*==exportEnd==*/

      /*自动选择所属公司类型*/
      companyChange(val) {
        let filterObj = this.companies.filter(item => {
          return item.ID == val
        })[0]
        this.editForm.companyType = filterObj.companyType
      }
    }
  }
</script>
